import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:uuid/uuid.dart';
import '../models/server_config.dart';
import '../providers/vpn_provider.dart';

class AddServerDialog extends StatefulWidget {
  const AddServerDialog({super.key});

  @override
  State<AddServerDialog> createState() => _AddServerDialogState();
}

class _AddServerDialogState extends State<AddServerDialog> with SingleTickerProviderStateMixin {
  final _formKey = GlobalKey<FormState>();
  late TabController _tabController;
  
  // 基础配置
  final _nameController = TextEditingController();
  final _addressController = TextEditingController();
  final _portController = TextEditingController(text: '443');
  final _userIdController = TextEditingController();
  final _alterIdController = TextEditingController(text: '0');
  final _remarksController = TextEditingController();
  final _groupController = TextEditingController();
  
  // 高级配置
  final _pathController = TextEditingController();
  final _hostController = TextEditingController();
  final _sniController = TextEditingController();
  final _alpnController = TextEditingController();
  final _fingerprintController = TextEditingController();
  
  String _selectedProtocol = 'vmess';
  String _selectedSecurity = 'auto';
  String _selectedNetwork = 'tcp';
  String? _selectedTls;
  
  final List<String> _protocols = ['vmess', 'vless', 'trojan', 'shadowsocks', 'socks'];
  final List<String> _securities = ['auto', 'aes-128-gcm', 'chacha20-poly1305', 'none'];
  final List<String> _networks = ['tcp', 'ws', 'grpc', 'http', 'h2'];
  final List<String> _tlsOptions = ['tls', 'xtls', 'reality'];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
  }

  @override
  void dispose() {
    _tabController.dispose();
    _nameController.dispose();
    _addressController.dispose();
    _portController.dispose();
    _userIdController.dispose();
    _alterIdController.dispose();
    _remarksController.dispose();
    _groupController.dispose();
    _pathController.dispose();
    _hostController.dispose();
    _sniController.dispose();
    _alpnController.dispose();
    _fingerprintController.dispose();
    super.dispose();
  }

  Future<void> _saveServer() async {
    if (!_formKey.currentState!.validate()) {
      return;
    }

    final vpnProvider = Provider.of<VpnProvider>(context, listen: false);
    
    // 简化：暂时不获取地理位置，可以后续通过测试Ping时获取
    final server = ServerConfig(
      id: const Uuid().v4(),
      name: _nameController.text.trim(),
      protocol: _selectedProtocol,
      address: _addressController.text.trim(),
      port: int.parse(_portController.text),
      userId: _userIdController.text.trim(),
      alterId: _alterIdController.text.trim(),
      security: _selectedSecurity,
      network: _selectedNetwork,
      path: _pathController.text.trim().isEmpty ? null : _pathController.text.trim(),
      host: _hostController.text.trim().isEmpty ? null : _hostController.text.trim(),
      tls: _selectedTls,
      sni: _sniController.text.trim().isEmpty ? null : _sniController.text.trim(),
      alpn: _alpnController.text.trim().isEmpty ? null : _alpnController.text.trim(),
      fingerprint: _fingerprintController.text.trim().isEmpty ? null : _fingerprintController.text.trim(),
      remarks: _remarksController.text.trim().isEmpty ? null : _remarksController.text.trim(),
      group: _groupController.text.trim().isEmpty ? null : _groupController.text.trim(),
    );

    await vpnProvider.addServer(server);

    if (mounted) {
      Navigator.pop(context);
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Row(
            children: [
              const Icon(Icons.check_circle, color: Colors.white),
              const SizedBox(width: 12),
              Text('Server "${server.name}" added successfully'),
            ],
          ),
          backgroundColor: Colors.green,
          behavior: SnackBarBehavior.floating,
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
      child: Container(
        constraints: const BoxConstraints(maxWidth: 600, maxHeight: 700),
        child: Column(
          children: [
            // 头部
            Container(
              padding: const EdgeInsets.all(20),
              decoration: BoxDecoration(
                color: Theme.of(context).colorScheme.primary,
                borderRadius: const BorderRadius.vertical(top: Radius.circular(20)),
              ),
              child: Row(
                children: [
                  const Icon(Icons.add_circle_outline, color: Colors.white, size: 28),
                  const SizedBox(width: 12),
                  const Expanded(
                    child: Text(
                      'Add Server',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  IconButton(
                    icon: const Icon(Icons.close, color: Colors.white),
                    onPressed: () => Navigator.pop(context),
                  ),
                ],
              ),
            ),
            
            // Tab 标签
            TabBar(
              controller: _tabController,
              tabs: const [
                Tab(icon: Icon(Icons.settings), text: 'Basic'),
                Tab(icon: Icon(Icons.tune), text: 'Advanced'),
              ],
            ),
            
            // Tab 内容
            Expanded(
              child: Form(
                key: _formKey,
                child: TabBarView(
                  controller: _tabController,
                  children: [
                    _buildBasicTab(),
                    _buildAdvancedTab(),
                  ],
                ),
              ),
            ),
            
            // 底部按钮
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Theme.of(context).brightness == Brightness.dark
                    ? Colors.grey.shade900.withOpacity(0.3)
                    : Colors.grey.shade50,
                border: Border(
                  top: BorderSide(
                    color: Theme.of(context).brightness == Brightness.dark
                        ? Colors.grey.shade700.withOpacity(0.5)
                        : Colors.grey.shade200,
                  ),
                ),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  TextButton(
                    onPressed: () => Navigator.pop(context),
                    child: const Text('Cancel'),
                  ),
                  const SizedBox(width: 12),
                  ElevatedButton.icon(
                    onPressed: _saveServer,
                    icon: const Icon(Icons.save),
                    label: const Text('Add Server'),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Theme.of(context).colorScheme.primary,
                      foregroundColor: Colors.white,
                      padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildBasicTab() {
    final isDark = Theme.of(context).brightness == Brightness.dark;
    final inputFillColor = isDark ? Colors.grey.shade900.withOpacity(0.3) : Colors.grey.shade50;
    
    return SingleChildScrollView(
      padding: const EdgeInsets.all(20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 服务器名称
          TextFormField(
            controller: _nameController,
            decoration: InputDecoration(
              labelText: 'Server Name *',
              hintText: 'e.g., US Server 01',
              prefixIcon: const Icon(Icons.label),
              border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
              filled: true,
              fillColor: inputFillColor,
            ),
            validator: (value) {
              if (value == null || value.trim().isEmpty) {
                return 'Server name is required';
              }
              return null;
            },
          ),
          const SizedBox(height: 16),
          
          // 协议选择
          DropdownButtonFormField<String>(
            value: _selectedProtocol,
            decoration: InputDecoration(
              labelText: 'Protocol *',
              prefixIcon: const Icon(Icons.security),
              border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
              filled: true,
              fillColor: inputFillColor,
            ),
            items: _protocols.map((protocol) {
              return DropdownMenuItem(
                value: protocol,
                child: Text(protocol.toUpperCase()),
              );
            }).toList(),
            onChanged: (value) {
              setState(() {
                _selectedProtocol = value!;
              });
            },
          ),
          const SizedBox(height: 16),
          
          // 服务器地址
          TextFormField(
            controller: _addressController,
            decoration: InputDecoration(
              labelText: 'Server Address *',
              hintText: 'e.g., example.com or 1.2.3.4',
              prefixIcon: const Icon(Icons.dns),
              border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
              filled: true,
              fillColor: inputFillColor,
            ),
            validator: (value) {
              if (value == null || value.trim().isEmpty) {
                return 'Server address is required';
              }
              return null;
            },
          ),
          const SizedBox(height: 16),
          
          // 端口
          TextFormField(
            controller: _portController,
            decoration: InputDecoration(
              labelText: 'Port *',
              hintText: 'e.g., 443',
              prefixIcon: const Icon(Icons.pin),
              border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
              filled: true,
              fillColor: inputFillColor,
            ),
            keyboardType: TextInputType.number,
            validator: (value) {
              if (value == null || value.trim().isEmpty) {
                return 'Port is required';
              }
              final port = int.tryParse(value);
              if (port == null || port < 1 || port > 65535) {
                return 'Port must be between 1 and 65535';
              }
              return null;
            },
          ),
          const SizedBox(height: 16),
          
          // UUID / 密码
          TextFormField(
            controller: _userIdController,
            decoration: InputDecoration(
              labelText: _selectedProtocol == 'shadowsocks' ? 'Password *' : 'UUID / User ID *',
              hintText: 'e.g., xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
              prefixIcon: const Icon(Icons.key),
              border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
              filled: true,
              fillColor: inputFillColor,
            ),
            validator: (value) {
              if (value == null || value.trim().isEmpty) {
                return 'User ID is required';
              }
              return null;
            },
          ),
          const SizedBox(height: 16),
          
          // AlterID (仅 VMess)
          if (_selectedProtocol == 'vmess') ...[
            TextFormField(
              controller: _alterIdController,
              decoration: InputDecoration(
                labelText: 'Alter ID',
                hintText: '0',
                prefixIcon: const Icon(Icons.numbers),
                border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
                filled: true,
                fillColor: inputFillColor,
              ),
              keyboardType: TextInputType.number,
            ),
            const SizedBox(height: 16),
          ],
          
          // 加密方式
          DropdownButtonFormField<String>(
            value: _selectedSecurity,
            decoration: InputDecoration(
              labelText: 'Security / Encryption',
              prefixIcon: const Icon(Icons.lock),
              border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
              filled: true,
              fillColor: inputFillColor,
            ),
            items: _securities.map((security) {
              return DropdownMenuItem(
                value: security,
                child: Text(security),
              );
            }).toList(),
            onChanged: (value) {
              setState(() {
                _selectedSecurity = value!;
              });
            },
          ),
          const SizedBox(height: 16),
          
          // 分组
          Consumer<VpnProvider>(
            builder: (context, vpnProvider, _) {
              final existingGroups = vpnProvider.groups.where((g) => g != 'All').toList();
              
              return Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  TextFormField(
                    controller: _groupController,
                    decoration: InputDecoration(
                      labelText: 'Group (Optional)',
                      hintText: 'e.g., USA, Premium, Free',
                      prefixIcon: const Icon(Icons.folder),
                      border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
                      filled: true,
                      fillColor: inputFillColor,
                    ),
                  ),
                  if (existingGroups.isNotEmpty) ...[
                    const SizedBox(height: 8),
                    Wrap(
                      spacing: 8,
                      children: existingGroups.map((group) {
                        return ActionChip(
                          label: Text(group),
                          onPressed: () {
                            setState(() {
                              _groupController.text = group;
                            });
                          },
                        );
                      }).toList(),
                    ),
                  ],
                ],
              );
            },
          ),
          const SizedBox(height: 16),
          
          // 备注
          TextFormField(
            controller: _remarksController,
            decoration: InputDecoration(
              labelText: 'Remarks (Optional)',
              hintText: 'Additional notes',
              prefixIcon: const Icon(Icons.note),
              border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
              filled: true,
              fillColor: inputFillColor,
            ),
            maxLines: 2,
          ),
        ],
      ),
    );
  }

  Widget _buildAdvancedTab() {
    final isDark = Theme.of(context).brightness == Brightness.dark;
    final inputFillColor = isDark ? Colors.grey.shade900.withOpacity(0.3) : Colors.grey.shade50;
    
    return SingleChildScrollView(
      padding: const EdgeInsets.all(20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 网络类型
          DropdownButtonFormField<String>(
            value: _selectedNetwork,
            decoration: InputDecoration(
              labelText: 'Network Type',
              prefixIcon: const Icon(Icons.wifi),
              border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
              filled: true,
              fillColor: inputFillColor,
            ),
            items: _networks.map((network) {
              return DropdownMenuItem(
                value: network,
                child: Text(network.toUpperCase()),
              );
            }).toList(),
            onChanged: (value) {
              setState(() {
                _selectedNetwork = value!;
              });
            },
          ),
          const SizedBox(height: 16),
          
          // TLS
          DropdownButtonFormField<String?>(
            value: _selectedTls,
            decoration: InputDecoration(
              labelText: 'TLS (Optional)',
              prefixIcon: const Icon(Icons.verified_user),
              border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
              filled: true,
              fillColor: inputFillColor,
            ),
            items: [
              const DropdownMenuItem(value: null, child: Text('None')),
              ..._tlsOptions.map((tls) {
                return DropdownMenuItem(
                  value: tls,
                  child: Text(tls.toUpperCase()),
                );
              }).toList(),
            ],
            onChanged: (value) {
              setState(() {
                _selectedTls = value;
              });
            },
          ),
          const SizedBox(height: 16),
          
          // Path (WebSocket/HTTP/H2)
          if (_selectedNetwork == 'ws' || _selectedNetwork == 'http' || _selectedNetwork == 'h2') ...[
            TextFormField(
              controller: _pathController,
              decoration: InputDecoration(
                labelText: 'Path',
                hintText: 'e.g., /ws or /path',
                prefixIcon: const Icon(Icons.route),
                border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
                filled: true,
                fillColor: inputFillColor,
              ),
            ),
            const SizedBox(height: 16),
          ],
          
          // Host
          TextFormField(
            controller: _hostController,
            decoration: InputDecoration(
              labelText: 'Host (Optional)',
              hintText: 'e.g., example.com',
              prefixIcon: const Icon(Icons.public),
              border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
              filled: true,
              fillColor: inputFillColor,
            ),
          ),
          const SizedBox(height: 16),
          
          // SNI
          if (_selectedTls != null) ...[
            TextFormField(
              controller: _sniController,
              decoration: InputDecoration(
                labelText: 'SNI (Optional)',
                hintText: 'e.g., example.com',
                prefixIcon: const Icon(Icons.fingerprint),
                border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
                filled: true,
                fillColor: inputFillColor,
              ),
            ),
            const SizedBox(height: 16),
          ],
          
          // ALPN
          TextFormField(
            controller: _alpnController,
            decoration: InputDecoration(
              labelText: 'ALPN (Optional)',
              hintText: 'e.g., h2,http/1.1',
              prefixIcon: const Icon(Icons.alt_route),
              border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
              filled: true,
              fillColor: inputFillColor,
            ),
          ),
          const SizedBox(height: 16),
          
          // Fingerprint
          TextFormField(
            controller: _fingerprintController,
            decoration: InputDecoration(
              labelText: 'Fingerprint (Optional)',
              hintText: 'e.g., chrome, firefox, safari',
              prefixIcon: const Icon(Icons.psychology),
              border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
              filled: true,
              fillColor: inputFillColor,
            ),
          ),
          
          const SizedBox(height: 24),
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Theme.of(context).brightness == Brightness.dark
                  ? Colors.blue.shade900.withOpacity(0.2)
                  : Colors.blue.shade50,
              borderRadius: BorderRadius.circular(12),
              border: Border.all(
                color: Theme.of(context).brightness == Brightness.dark
                    ? Colors.blue.shade700.withOpacity(0.5)
                    : Colors.blue.shade200,
              ),
            ),
            child: Row(
              children: [
                Icon(Icons.info_outline, color: Colors.blue.shade700),
                const SizedBox(width: 12),
                Expanded(
                  child: Text(
                    'Advanced settings are optional and only needed for specific server configurations.',
                    style: TextStyle(
                      fontSize: 12,
                      color: Theme.of(context).brightness == Brightness.dark
                          ? Colors.blue.shade300
                          : Colors.blue.shade900,
                      height: 1.4,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
